import React, { useState, useEffect } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import Item from './components/Item/Item'
import './App.css'
export default function App() {
  const [todos, setTodos] = useState([
    {
      id: 1,
      todoName: '吃饭',
      isDone: false,
    },
    {
      id: 2,
      todoName: '睡觉',
      isDone: true,
    },
  ])

  useEffect(() => {
    // 添加订阅
    const addId = PubSub.subscribe('add', (topic, todoName) => {
      // setTodos(newList)
      setTodos((newTodos) => {
        // 根据任务名创建任务对象
        const todo = {
          todoName,
          isDone: false,
          // 每次添加,都找到原来数组中最后一个数据的id,加1
          // 如果数组中没有数据,则第一条数据的id就是1
          id: newTodos.length ? newTodos[newTodos.length - 1].id + 1 : 1, //不和其他数据的id重复,并且也必须是整数
        }
        // newTodos 一定是最新的todos数据
        const newList = [...newTodos]
        newList.push(todo)
        return newList
      })
    })
    // 修改订阅
    const updateId = PubSub.subscribe('update', (topic, id) => {
      setTodos((newTodos) => {
        const newList = newTodos.map((item) => {
          if (item.id === id) item.isDone = !item.isDone
          return item
        })
        return newList
      })
    })
    return () => {
      PubSub.unsubscribe(addId)
      PubSub.unsubscribe(updateId)
    }
  }, [])
  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {todos.map((item) => {
              return <Item key={item.id} todo={item}></Item>
            })}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
